﻿using System;
using System.Collections.Generic;
using Opalis.QuickIntegrationKit;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Collections;

namespace Active_Directory
{
    [OpalisObject("Remove User From Group", ShowFilters = false)]
    class RemoveUserFromGroup : IOpalisObject
    {
        private ConnectionCredentials credentials;

        [OpalisConfiguration]
        public ConnectionCredentials Credentials
        {
            get { return credentials; }
            set { credentials = value; }
        }

        public void Design(IOpalisDesigner designer)
        {
            designer.AddInput("Group LDAP Path").WithDefaultValue("LDAP://CN=GroupName,OU=Container,DC=Contoso,DC=Com");
            designer.AddInput("User LDAP Path").WithDefaultValue("LDAP://CN=GroupName,OU=Container,DC=Contoso,DC=Com");
            designer.AddOutput("Removed User LDAP Path").AsString();
        }

        public void Execute(IOpalisRequest request, IOpalisResponse response)
        {
            string GroupLDAPPath = request.Inputs["Group LDAP Path"].AsString();
            string UserLDAPPath = request.Inputs["User LDAP Path"].AsString();

            DirectoryEntry dirEntry = new DirectoryEntry(GroupLDAPPath, credentials.UserName + "@" + credentials.Domain, credentials.Password);

            string FormattedUserDN = UserLDAPPath.Substring(7);
            dirEntry.Properties["member"].Remove(FormattedUserDN);
            dirEntry.CommitChanges();
            dirEntry.Close();

            response.Publish("Removed User LDAP Path", UserLDAPPath);
        }
    }
}
